<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="选择设备" prop="deviceId">
            <select-device v-model="state.device" placeholder="选择设备" @on-select="handleSelectDevice" />
          </el-form-item>
          <el-form-item label="选择属性" prop="properties">
            <el-select v-model="state.properties" :multiple="true">
              <el-option v-for="pro in state.thingModelItems" :label="pro.name" :value="pro.identifier" :key="pro.identifier" />
            </el-select>
          </el-form-item>
          <el-form-item label="时间区间" prop="startTime">
            <el-date-picker
              v-model="state.queryTime"
              type="datetimerange"
              :picker-options="state.pickerOptions"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              @change="handleQuery"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      
      <template v-for="(item, index) in state.dataList" :key="index">
        <PropertyChart :name="item.name" :properties="item.data"></PropertyChart>
      </template>
    </el-card>
  </div>
</template>

<script setup name="Demo" lang="ts">
import { ComponentInternalInstance } from 'vue'
import { FormInstance } from 'element-plus'
import { queryData } from './api/index'
import { AnalyseQueryVO } from './api/types'

import SelectDevice from '@/components/YtSelect/select-device.vue'
import PropertyChart from './modules/PropertyChart.vue'
import { getObjectModel } from '@/views/iot/equipment/api/products.api'


const { proxy } = getCurrentInstance() as ComponentInternalInstance

const loading = ref(true)
const showSearch = ref(true)
const ids = ref<Array<string | number>>([])
const single = ref(true)
const multiple = ref(true)

const queryFormRef = ref<FormInstance>()

const queryParams = reactive<AnalyseQueryVO>({
  deviceId: '',
  properties: [],
  start: undefined,
    end: undefined,
    downsample: 0,
})


const state = reactive<any>({
  loading: false,
  device: null,
  thingModelItems: [],
  thingModelItemMap:{},
  properties: [],
  propertyHistory: {
    name: '',
    data: [],
  },
  dataType: '',
  currHistoryProperty: {},
  dataList:[],
  queryTime: [new Date(new Date().getTime() - 1 * 3600 * 1000), new Date(new Date().getTime() + 1 * 3600 * 1000)],
  pickerOptions: {
    shortcuts: [
      {
        text: '最近1小时',
        onClick(picker) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000)
          picker.$emit('pick', [start, end])
        },
      },
      {
        text: '最近6小时',
        onClick(picker) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 6)
          picker.$emit('pick', [start, end])
        },
      },
      {
        text: '最近1天',
        onClick(picker) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24)
          picker.$emit('pick', [start, end])
        },
      },
      {
        text: '最近5天',
        onClick(picker) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 5)
          picker.$emit('pick', [start, end])
        },
      },
    ],
  },
})


const handleSelectDevice = (device) => {
  if (!device.productKey) return
  state.device=device
  getObjectModel(device.productKey).then((res) => {
    const data = res.data || {}
    state.properties.length=0
    state.thingModelItems.length=0
    initThingModel(device.productKey, data)
  })
}

const initThingModel = (pk, res) => {
  res?.model?.properties &&
    res.model.properties.forEach((p) => {
      state.thingModelItems.push({
        identifier: p.identifier,
        name: p.name,
        unit:p.unit,
      })

      state.thingModelItemMap[p.identifier]={  identifier: p.identifier,
        name: p.name,
        unit:p.unit}

    })
}

/** 查询 */
const handleQuery = async () => {
  loading.value = true
  var propertyCode=state.properties[0]
  var property=state.thingModelItemMap[propertyCode]
  queryData({
    deviceId: state.device.deviceId,
    properties: state.properties,
    start: state.queryTime[0].getTime(),
    end: state.queryTime[1].getTime()
  }).then((res) => {
      state.dataList=res.data.list
    })
    .finally(() => {
      loading.value = false
    })
  loading.value = false
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  state.device=null
  state.properties.length=0
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: AnalyseQueryVO[]) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}


onMounted(() => {
 // getList()
})
</script>
